package java_util_concurrent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import util.LogUtil;

public class Test_ExecutorService_CyclicBarrier {
	private static final String TAG = "Test_ExecutorService_CyclicBarrier";

	public static void main(String[] argz) {
		Test_ExecutorService_CyclicBarrier t = new Test_ExecutorService_CyclicBarrier();

		t.test();
	}

	public void test() {
		CyclicBarrier barrier = new CyclicBarrier(3);
		ExecutorService exec = Executors.newFixedThreadPool(3);

		LogUtil.d(TAG, now() + " test: begin...");

		exec.submit(new Tour(barrier, "WalkTour", timeWalk));
		exec.submit(new Tour(barrier, "SelfTour", timeSelf));
		exec.submit(new Tour(barrier, "BusTour", timeBus));

		LogUtil.d(TAG, now() + " test: exec.shutdown()");

		exec.shutdown();
	}

	static String now() {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		return sdf.format(new Date()) + ": ";
	}

	private static int[] timeWalk = { 5, 8, 15, 15, 10 }; // 徒步需要的时间: Shenzhen,
															// Guangzhou,
															// Shaoguan,
															// Changsha, Wuhan
	private static int[] timeSelf = { 1, 3, 4, 4, 5 }; // 自驾游
	private static int[] timeBus = { 2, 4, 6, 6, 7 }; // 旅游大巴

	static class Tour implements Runnable {
		private int[] times;
		private CyclicBarrier barrier;
		private String tourName;

		public Tour(CyclicBarrier barrier, String tourName, int[] times) {
			this.times = times;
			this.tourName = tourName;
			this.barrier = barrier;
		}

		public void run() {
			try {
				Thread.sleep(times[0] * 1000);
				LogUtil.d(TAG, now() + tourName + " Reached Shenzhen");
				barrier.await();
				Thread.sleep(times[1] * 1000);
				LogUtil.d(TAG, now() + tourName + " Reached Guangzhou");
				barrier.await();
				Thread.sleep(times[2] * 1000);
				LogUtil.d(TAG, now() + tourName + " Reached Shaoguan");
				barrier.await();
				Thread.sleep(times[3] * 1000);
				LogUtil.d(TAG, now() + tourName + " Reached Changsha");
				barrier.await();
				Thread.sleep(times[4] * 1000);
				LogUtil.d(TAG, now() + tourName + " Reached Wuhan");
				barrier.await();
			} catch (InterruptedException e) {
			} catch (BrokenBarrierException e) {
			}
		}
	}
}
